package servlets;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import actionForms.updateContactValidationForm;
import domain.Address;
import domain.Contact;
import domain.IDAOContact;
import domain.PhoneNumber;

public class updateContactAction extends Action {

	public ActionForward execute(final ActionMapping pMapping, ActionForm pForm, final HttpServletRequest pRequest, final HttpServletResponse pResponse) {
		final updateContactValidationForm lForm = (updateContactValidationForm) pForm;
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(pRequest.getSession().getServletContext());
		IDAOContact dao = (IDAOContact) context.getBean("daoContact");

		Address address = new Address();
		address.setStreet(lForm.getStreet());
		address.setCity(lForm.getCity());
		address.setCountry(lForm.getCountry());
		address.setZip(lForm.getZip());

		Set<PhoneNumber> phones = new HashSet<PhoneNumber>();
		if (lForm.getNumPhoneMobile() != null && !lForm.getNumPhoneMobile().equals("")) {
			PhoneNumber phoneNumberMobile = new PhoneNumber();
			phoneNumberMobile.setPhoneKind("numPhoneMobile");
			phoneNumberMobile.setPhoneNumber(lForm.getNumPhoneMobile());
			phones.add(phoneNumberMobile);
		}
		if (lForm.getNumPhoneHome() != null && !lForm.getNumPhoneHome().equals("")) {
			PhoneNumber phoneNumberHome = new PhoneNumber();
			phoneNumberHome.setPhoneKind("numPhoneHome");
			phoneNumberHome.setPhoneNumber(lForm.getNumPhoneHome());
			phones.add(phoneNumberHome);
		}
		if (lForm.getNumPhoneDesktop() != null && !lForm.getNumPhoneDesktop().equals("")) {
			PhoneNumber phoneNumberDesktop = new PhoneNumber();
			phoneNumberDesktop.setPhoneKind("numPhoneDesktop");
			phoneNumberDesktop.setPhoneNumber(lForm.getNumPhoneDesktop());
			phones.add(phoneNumberDesktop);
			phones.add(phoneNumberDesktop);
		}
		
		boolean result = dao.modifyContact(lForm.getId(), lForm.getFirstname(), lForm.getLastname(), lForm.getEmail(), address, phones, lForm.getBooks(), lForm.getSIRET());
		pRequest.setAttribute("type", "show");
		List<Contact> contacts = dao.getAllContact();
		pRequest.setAttribute("contacts", contacts);
		
        if (result) {
        	pRequest.setAttribute("contactUpdated", true);
		} else {
			pRequest.setAttribute("contactUpdated", false);
		}        
        
        return pMapping.findForward("resultsPage");		
	}
}